package com.akk.business;

import com.akk.module.avs.entity.*;
import com.akk.module.avs.enums.RecordStatus;
import com.akk.module.avs.model.request.AvsYbApplyLoanReq;
import com.akk.module.avs.model.response.AvsYbLoanRes;
import com.akk.module.avs.service.AvsYbLoanAccessService;
import com.akk.module.avs.service.AvsYbLoanRecordService;
import com.akk.module.avs.service.AvsYbLoanService;
import com.akk.module.avs.service.AvsYbLoanTypeService;
import com.akk.utils.RestResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AvsYbLoanBusiness {

    @Autowired
    private AvsYbLoanService ybLoanService;

    @Autowired
    private AvsYbLoanRecordService recordService;

    @Autowired
    private AvsYbLoanTypeService ybLoanTypeService;

    @Autowired
    private AvsYbLoanAccessService loanAccessService;

    public RestResponse loanList(String appId,Long typeId){
        if (StringUtils.isEmpty(appId))
            return RestResponse.build("1","参数缺失",null);
        Map params = new HashMap();
        params.put("appId",appId);
        params.put("status","0");
        params.put("typeId",typeId);
        List<AvsYbLoan> list = ybLoanService.findByParams(params);
        return RestResponse.build(list);
    }

    public RestResponse loanInfo(Long loanId){
        AvsYbLoanRes loan = ybLoanService.findById(loanId);
        return RestResponse.build(loan);
    }

    public RestResponse applyLoan(AvsYbApplyLoanReq req, BindingResult bindingResult){
        if (bindingResult.hasErrors())
            return RestResponse.build("1",bindingResult.getFieldError().getDefaultMessage(),"");
        AvsYbLoanUser user = recordService.saveUserWithReturn(req);
        AvsYbLoanRecord record = new AvsYbLoanRecord();
        record.setCreateDate(new Date());
        record.setLoanUserId(user.getLoanUserId());
        record.setLoanId(req.getLoanId());
        record.setStatus(RecordStatus.PENDING.getValue());
        record.setAppId(req.getAppId());
        recordService.save(record);
        return RestResponse.build("200","success","");
    }

    public RestResponse loanAccess(AvsYbLoanAccess access,BindingResult bindingResult){
        if (bindingResult.hasErrors())
            return RestResponse.build("1",bindingResult.getFieldError().getDefaultMessage());
        access.setStatus(0);
        access.setCreateDate(new Date());
        loanAccessService.save(access);
        return RestResponse.build("success");
    }

    public RestResponse loanTypes(String appId){
        if (StringUtils.isEmpty(appId))
            return RestResponse.build("1","参数缺失",null);
        List<AvsYbLoanType> list = ybLoanTypeService.findAll(appId);
        return RestResponse.build(list);
    }

}
